#!/bin/bash

# Dify连接测试脚本

set -e

echo "=================================="
echo "  Dify连接测试"
echo "=================================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 从配置文件读取配置
CONFIG_FILE="src/main/resources/application.yml"

if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}错误: 找不到配置文件 $CONFIG_FILE${NC}"
    exit 1
fi

BASE_URL=$(grep -A 2 "dify:" "$CONFIG_FILE" | grep "base-url:" | awk '{print $2}')
API_KEY=$(grep -A 3 "dify:" "$CONFIG_FILE" | grep "key:" | awk '{print $2}')

echo -e "${BLUE}当前配置:${NC}"
echo "  Base URL: $BASE_URL"
echo "  API Key: ${API_KEY:0:15}..."
echo ""

# 测试1: 检查Dify服务
echo "测试 1: 检查Dify服务"
echo "-----------------------------------"

DIFY_HOST=$(echo $BASE_URL | sed 's|/v1||' | sed 's|http://||' | sed 's|https://||' | cut -d: -f1)
DIFY_PORT=$(echo $BASE_URL | grep -o ':[0-9]*' | sed 's/://' || echo "80")

if [ "$DIFY_HOST" == "localhost" ] || [ "$DIFY_HOST" == "127.0.0.1" ]; then
    if docker ps | grep -q dify; then
        echo -e "${GREEN}✓ Dify Docker容器正在运行${NC}"
    else
        echo -e "${YELLOW}⚠ 未检测到Dify Docker容器${NC}"
    fi
fi

# 测试Dify服务是否可访问
if curl -s --connect-timeout 5 "${BASE_URL%/v1}" > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Dify服务可访问${NC}"
else
    echo -e "${RED}✗ 无法访问Dify服务${NC}"
    echo "  请检查:"
    echo "  - Dify是否正在运行"
    echo "  - Base URL是否正确: $BASE_URL"
    echo "  - 网络连接是否正常"
    exit 1
fi

echo ""

# 测试2: 检查后端服务
echo "测试 2: 检查后端服务"
echo "-----------------------------------"

if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ 后端服务正在运行 (端口8080)${NC}"
    
    # 等待服务完全启动
    sleep 2
    
    # 测试健康检查
    if curl -s http://localhost:8080/actuator/health > /dev/null 2>&1; then
        echo -e "${GREEN}✓ 后端服务健康检查通过${NC}"
    fi
else
    echo -e "${RED}✗ 后端服务未运行${NC}"
    echo "  请先启动后端服务: mvn spring-boot:run"
    exit 1
fi

echo ""

# 测试3: 测试问答API
echo "测试 3: 测试问答API"
echo "-----------------------------------"

echo "发送测试问题: '你好'"

RESPONSE=$(curl -s -X POST http://localhost:8080/api/qa/ask \
  -H "Content-Type: application/json" \
  -d '{"question":"你好","userId":1}' 2>&1)

if [ $? -eq 0 ]; then
    # 检查响应是否包含错误
    if echo "$RESPONSE" | grep -q "error"; then
        echo -e "${RED}✗ API调用失败${NC}"
        echo "响应: $RESPONSE"
        
        if echo "$RESPONSE" | grep -q "401"; then
            echo ""
            echo -e "${YELLOW}可能的原因:${NC}"
            echo "  - API密钥不正确"
            echo "  - API密钥已过期"
            echo "  - 使用了错误类型的密钥（需要app-开头的密钥）"
        elif echo "$RESPONSE" | grep -q "404"; then
            echo ""
            echo -e "${YELLOW}可能的原因:${NC}"
            echo "  - Base URL不正确"
            echo "  - Dify API端点路径错误"
        elif echo "$RESPONSE" | grep -q "timeout"; then
            echo ""
            echo -e "${YELLOW}可能的原因:${NC}"
            echo "  - Dify响应太慢"
            echo "  - 网络连接问题"
        fi
        exit 1
    else
        echo -e "${GREEN}✓ API调用成功${NC}"
        echo ""
        echo "响应内容:"
        echo "$RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$RESPONSE"
        
        # 检查是否有知识库内容
        if echo "$RESPONSE" | grep -q '"hasKnowledge":true'; then
            echo ""
            echo -e "${GREEN}✓ 知识库连接正常${NC}"
        elif echo "$RESPONSE" | grep -q '"hasKnowledge":false'; then
            echo ""
            echo -e "${YELLOW}⚠ 知识库为空或无相关内容${NC}"
            echo "  建议: 在Dify控制台上传文档到知识库"
        fi
    fi
else
    echo -e "${RED}✗ 无法连接到后端服务${NC}"
    exit 1
fi

echo ""

# 测试4: 检查前端服务
echo "测试 4: 检查前端服务"
echo "-----------------------------------"

if lsof -Pi :5173 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${GREEN}✓ 前端服务正在运行 (端口5173)${NC}"
    echo "  访问地址: http://localhost:5173"
else
    echo -e "${YELLOW}⚠ 前端服务未运行${NC}"
    echo "  启动前端: cd frontend && npm run dev"
fi

echo ""
echo "=================================="
echo "  测试完成"
echo "=================================="
echo ""

# 总结
echo -e "${BLUE}测试总结:${NC}"
echo "  ✓ 表示测试通过"
echo "  ⚠ 表示警告（不影响核心功能）"
echo "  ✗ 表示测试失败（需要修复）"
echo ""

echo -e "${BLUE}下一步:${NC}"
echo "  1. 访问前端: http://localhost:5173"
echo "  2. 进入'智能问答'页面测试问答功能"
echo "  3. 如果返回'无相关知识'，在Dify控制台上传文档"
echo "  4. 查看完整设置指南: cat DIFY_SETUP_GUIDE.md"
echo ""
